<!--
 * @Description:
 * @Author: william
 * @Date: 2025-02-17 16:47:40
 * @LastEditors: william
 * @LastEditTime: 2025-09-10 13:50:11
-->
<template>
  <BaseDialog
    v-model="dialogVisible"
    :title="title"
    width="850px"
    :before-close="handleClose"
  >
    <el-form
      ref="refDialogForm"
      v-loading="formLoading"
      class="set-dialog-form"
      :label-width="language === 'en' ? '180px' : '80px'"
      :model="formData"
      :rules="rules"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('userCenter.belongDept')" prop="deptIds">
            <CascaderDept
              v-model="formData.deptIds"
              v-model:id="localDeptId"
              style="width: 100%"
              :disabled="type === 'edit'"
              :label="$t('userCenter.belongDept')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="base64Image">
            <template #label>
              <label>头像</label>
            </template>
            <el-upload
              style="width: 100%"
              v-model:file-list="fileList"
              :limit="1"
              accept="image/*"
              :action="action"
              :headers="uploadHeaders"
              name="file"
              :auto-upload="true"
              :on-change="handleChange"
              :on-exceed="handleExceed"
              :on-preview="handlePicturePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
            >
              <el-button type="primary">上传头像</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('public.userName')" prop="userName">
            <InputUserName
              v-model="formData.userName"
              :disabled="type === 'edit'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('public.nickName')" prop="nickName">
            <TextInput
              v-model="formData.nickName"
              :label="$t('public.nickName')"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="type === 'add'" :span="12">
          <el-form-item :label="$t('public.password')" prop="password">
            <TextInput
              v-model="formData.password"
              :label="$t('public.password')"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="type === 'add'" :span="12">
          <el-form-item
            :label="$t('public.confirmPassword')"
            prop="confirmPassword"
          >
            <TextInput
              v-model="formData.confirmPassword"
              :label="$t('public.confirmPassword')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('public.phone')" prop="phone">
            <InputPhone v-model="formData.phone" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('public.email')" prop="email">
            <TextInput v-model="formData.email" :label="$t('public.email')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('userCenter.role')" prop="roleIdList">
            <SelectRole
              v-model:list="roleOptions"
              v-model="formData.roleIdList"
            />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item :label="$t('userCenter.dataPerm')" prop="dataPerm">
            <el-select
              v-model="formData.dataPerm"
              :placeholder="
                g_rules.zhAndEnShowMsg(
                  g_t('public.pleaseSelect'),
                  $t('userCenter.dataPerm')
                )
              "
            >
              <el-option
                v-for="item in g_options.dataPermOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col> -->
      </el-row>
    </el-form>
    <template #footer>
      <div class="form-dialog-footerr">
        <el-button plain @click="handleClose">{{
          $t('public.cancel')
        }}</el-button>
        <el-button type="primary" @click="handleSubmitForm">{{
          $t('public.confirm')
        }}</el-button>
      </div>
    </template>
  </BaseDialog>

  <el-image-viewer
    v-if="showPreview"
    :url-list="[formData.base64Image]"
    show-progress
    :initial-index="0"
    @close="showPreview = false"
  />
</template>

<script setup>
import { getUmsToken } from '@/utils/cookies'

const props = defineProps({
  type: {
    type: String,
    default: 'add' // add | edit
  },
  deptId: {
    type: String,
    default: ''
  },
  id: {
    type: String,
    default: ''
  }
})
const localDeptId = ref(props.deptId)

const emit = defineEmits(['update'])
const dialogVisible = defineModel({
  type: Boolean,
  default: false
})
const { language } = storeToRefs(useAppStore())
const title = computed(() =>
  props.type === 'add' ? g_t('public.create') : g_t('public.edit')
)

const refDialogForm = ref(null)
const formLoading = ref(false)
const formData = ref({
  deptIds: [],
  deptId: '',
  base64Image: '',
  avatar: '',
  userName: '',
  nickName: '',
  password: '',
  confirmPassword: '',
  phone: '',
  email: '',
  roleIdList: []
  // dataPerm: ''
})
const rules = {
  deptIds: g_rules.selectRule(g_t('userCenter.belongDept')),
  base64Image: g_rules.uploadFileRule('头像'),
  userName: g_rules.userName,
  nickName: g_rules.commonInputText(g_t('public.nickName')),
  password: g_rules.password,
  confirmPassword: g_rules.confirmPassword(formData.value, 'password'),
  phone: g_rules.phone({
    required: false
  }),
  email: g_rules.email({
    required: false
  })
  // roleIdList: g_rules.selectRule(g_t('userCenter.role'))
  // dataPerm: g_rules.selectRule(g_t('userCenter.dataPerm'))
}
const fileList = ref([])
const roleOptions = ref([])
const roleList = ref([])
const action = ref(import.meta.env.VITE_APP_BASE_API + '/file/upload')
const uploadHeaders = ref({
  Authorization: 'Bearer' + ' ' + getUmsToken(),
  lang: g_https.headersLang(),
  timeout: 10000
})
// 弹框参数
const showPreview = ref(false)

watch(
  () => formData.value.base64Image,
  nv => {
    refDialogForm.value.validateField(['base64Image'])
  }
)

watch(
  () => roleOptions.value,
  nv => {
    getRoleId()
  },
  {
    deep: true
  }
)

onMounted(() => {
  props.type === 'edit' && getFormData()
})

// 根据角色的label获取value
const getRoleId = _ => {
  roleOptions.value.forEach(item => {
    if (roleList.value.includes(item.label)) {
      formData.value.roleIdList.push(item.value)
    }
  })
}

const getFormData = () => {
  g_api.userCenter
    .apiUserDetail({
      deptId: props.deptId,
      userId: props.id
    })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        g_utils.assignFormData(formData.value, data)
        formData.value.deptName = data.deptName
        formData.value.userId = data.userId
        roleList.value = data.roleList
        formData.value.base64Image = data.avatar || ''
        if (data.avatar) {
          fileList.value = [
            {
              name: data.avatar,
              url: data.avatar
            }
          ]
        }
        getRoleId()
        console.log('formData.value', formData.value)
      }
    })
}

const handleChange = (file, files) => {
  // console.log('handleChange', file, files)
  // // 读取新选择的文件并添加到预览数组
  // const reader = new FileReader()
  // reader.onload = e => {
  //   formData.value.base64Image = e.target.result
  // }
  // reader.readAsDataURL(file.raw)
}

const handleExceed = (files, uploadFiles) => {
  // console.log('handleExceed', files, uploadFiles)
  ElMessage.warning(g_t('rule.uploadNumLargeTips'))
}

const handlePicturePreview = file => {
  console.log('handlePicturePreview', file)
  showPreview.value = true
}

const handleRemove = file => {
  console.log('handleRemove', file)
  formData.value.base64Image = ''
  formData.value.avatar = ''
}

const handleSuccess = (res, file, files) => {
  console.log('handleSuccess', res, file, files)
  if (res.code === '200' && res.data) {
    ElMessage.success(res.message)
    formData.value.avatar = res.data.url
    // 读取新选择的文件并添加到预览数组
    const reader = new FileReader()
    reader.onload = e => {
      formData.value.base64Image = e.target.result
    }
    reader.readAsDataURL(file.raw)
  } else {
    formData.value.base64Image = ''
    formData.value.avatar = ''
  }
}

const handleClose = () => {
  dialogVisible.value = false
}

const handleSubmitForm = () => {
  if (formLoading.value) return
  refDialogForm.value.validate(valid => {
    console.log(formData.value)
    if (!valid) return
    formLoading.value = true
    const urlMethod =
      props.type === 'add'
        ? g_api.userCenter.apiUserCreate
        : g_api.userCenter.apiUserUpdate
    const { deptIds } = formData.value
    urlMethod({
      ...formData.value,
      deptId: deptIds[deptIds.length - 1] || ''
    })
      .then(res => {
        if (res.code === '200') {
          ElMessage({
            message: res.message,
            type: 'success'
          })
          handleClose()
          emit('update')
        }
      })
      .finally(() => {
        formLoading.value = false
      })
  })
}
</script>

<style scoped lang="scss"></style>
